#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>

#include "util.h"

const list_str_ipaddrs UrlToIpAddress(const std::string& url){
    struct hostent* phostent = nullptr;
    list_str_ipaddrs strIpaddrs;
    if (nullptr == (phostent = gethostbyname(url.c_str()))){
        return strIpaddrs;
    }

    switch(phostent->h_addrtype){
        case AF_INET:
        case AF_INET6:
        {
            char str[32] = {"\0"};
            for (char** paddrlist = phostent->h_addr_list; nullptr != *paddrlist; ++paddrlist){
                strIpaddrs.push_back(inet_ntop(phostent->h_addrtype, *paddrlist, str, sizeof(str)));

            }
            break;
        }
        default:
            break;
    }

    return strIpaddrs;
}

void PrintListStrIpaddress(const list_str_ipaddrs& listStrIpaddress ){
    std::cout<<"list ipaddress:\n";
    for (auto ipaddr : listStrIpaddress){
        std::cout<<ipaddr<<std::endl;
    }
    std::cout<<"end list ipaddress:\n";
}

unsigned int HashKey(const char* szkey){
    register unsigned int h;
    register unsigned char *p;
    for(h=0, p = (unsigned char *)szkey; *p ; p++){
        h = 31 * h + *p;
    }

    return h;
}

std::string Int2String(const int n){
    return std::to_string(n);
}